package models;

import com.avaje.ebean.Model;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import play.api.libs.json.Json;
import play.data.format.Formats;
import play.data.validation.Constraints;
import scala.util.parsing.json.JSONArray;
import scala.util.parsing.json.JSONArray$;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.*;

/**
 * Bill entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "bill")
public class Bill extends Model{

	// Fields
	@Id
    @Constraints.Min(10)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
	public Long billId;

    @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    @JoinColumn(name = "user_id")
    @JsonManagedReference
	public User user;

    @Formats.DateTime(pattern = "yyyy-MM-dd HH:mm:ss")
	public Date billCreatetime = new Date();

    @Column(name = "bill_status")
	public Integer billStatus;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "bill")
    public Set<BillItem> billItems = new HashSet<BillItem>(0);

    @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    @JoinColumn(name = "customer_id", nullable = false)
    @JsonManagedReference
    public Customer customer;

    public static Finder<Long, Bill> find = new Finder<>(Bill.class);

    public static List<Bill> all() {
        return find.all();
    }

    public String sum(){
        float sum = 1;
        for(BillItem item : this.billItems){
            if(item.billItemStatus == 1){
                sum = Float.sum(sum, Float.parseFloat(BillItem.find.byId(item.billItemId).billItemSumPrice));
            }
        }
        return String.format("%.2f",sum);
    }


    public void billItemsInfo(){
        for(BillItem item : this.billItems){
            BillItem newItem = BillItem.find.byId(item.billItemId);
            item.billItemSum = newItem.billItemSum;
            item.billItemSumPrice = newItem.billItemSumPrice;
            item.billItemStatus = newItem.billItemStatus;
            item.product= newItem.product;
        }
    }
}